<?php
/**
 * ProfileController is the controller for business profile.
 * 
 * LBB Solutions Oy 版权所有 © 2013
 */
class ProfileController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * The billing page for merchant invoices.
	 */
	public function actionBilling() {
		$sql_billing = 'SELECT id, invoice_no, invoice_url, invoice_date, due_date, 
			total_price, status, paid_time, service_end_date
			FROM tbl_merchant_billing
			WHERE id_merchant=:id_merchant
			ORDER BY create_time DESC ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_billing);
		$rows = $command->queryAll(true, array(
			':id_merchant' => Yii::app()->user->id
		));
		$connection->active = false;
		$this->render('billing', array(
			'rows' => $rows,
		));
	}
	
	public function actionInvoiceDownload($id) {
		$sql_billing = 'SELECT invoice_no FROM tbl_merchant_billing WHERE id=:id ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_billing);
		$row = $command->queryRow(true, array(
			':id' => $id
		));
		$connection->active = false;
		if (empty($row['invoice_no'])) {
			throw new CHttpException(404, 'The downloading file does not exist.');
		}
		
		$id_merchant = Yii::app()->user->id;
		$path = Yii::app()->basePath . "/../../upload/merchants/{$id_merchant}/{$row['invoice_no']}.pdf";
		if (file_exists($path)) {
			return Yii::app()->getRequest()->sendFile($row['invoice_no'] . '.pdf', @file_get_contents($path));
		} else {
			throw new CHttpException(404, 'The downloading file does not exist.');
		}
	}
	
	/**
	 * Give a step guid when there is no profile, tags, default offer picture
	 */
	public function actionIndex()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		
		//1. fetch merchant tags
		$sql_merchant = 'SELECT t.cuisine_type, t.cuisine_style, t.meal_served, t.payment_options, t.service_languages, 
			t.alcohol_license, t.dining_ambience, t.car_parking, t.additional_details
			FROM tbl_merchant_tags t
			WHERE t.id_merchant=:id_merchant ';
		$params = array(':id_merchant'=>Yii::app()->user->id);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, $params);
		
		//2. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$aHours = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->render('index', array(
			'model' => $model,
			'tag' => $row,
			'aHours' => $aHours,
		));
	}
	
	/**
	 * List the location according to merchant's address
	 */
	public function actionLocation()
	{
		$address = Yii::app()->user->getState('address');
		if (empty($address)) {
			$location_list = array();
		} else {
			$address = $address . ', ' . Yii::app()->user->getState('postcode') . ' ' . Yii::app()->user->getState('city');
			$location_list = BUtils::getGoogleLocationList('Ratapihantie');
		}
		
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('location', array(
				'rows' => $location_list,
			));
		} else {
			$this->render('location', array(
				'rows' => $location_list,
			));
		}
	}
	
	/**
	 * List the business area
	 */
	public function actionBizArea()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$city_key = Yii::app()->request->getParam('city_key');
		if (empty($city_key)) {
			$sql_areas = 'SELECT biz_area AS value FROM tbl_sys_area_city WHERE city_key IN (:city1, :city2, :city3) ORDER BY biz_area ';
			$params = array(':city1' => 'helsinki', ':city2' => 'espoo', ':city3' => 'vantaa');
		} else {
			$city_key = strtolower($city_key);
			$sql_areas = 'SELECT biz_area AS value FROM tbl_sys_area_city WHERE city_key=:city_key ORDER BY biz_area ';
			$params = array(':city_key' => $city_key);
		}
		//fetch cities form merchant accounts
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_areas);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->renderPartial('_biz_area', array(
			'rows' => $rows,
		));
	}
	
	/**
	 * List the location according to merchant's address
	 */
	public function actionSaveLocation()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$latitude = Yii::app()->request->getParam('lat');
		$longitude = Yii::app()->request->getParam('lng');
		if (!empty($latitude) and !empty($longitude)) {
			Yii::app()->user->setState('latitude', $latitude);
			Yii::app()->user->setState('longitude', $longitude);
		}
	}
	
	public function actionAccount()
	{
		$model_email = $this->loadModel(Yii::app()->user->id);
		$model_email->setScenario('account_email');
		
		$model_password = $this->loadModel(Yii::app()->user->id);
		$model_password->setScenario('account_password');
		
		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			if (isset($_POST['MerchantForm']['new_password'])) {
				$model_password->attributes = $_POST['MerchantForm'];
				$model_password->new_password = $_POST['MerchantForm']['new_password'];
				if ($model_password->validate()) {
					//change password function
					$pasword_in_db = BUtils::Hash32(md5($model_password->new_password));
					$sql_update = 'UPDATE tbl_merchant_account SET update_timestamp=NOW(), password=:password WHERE id=:id ';
					$params = array(':id' => Yii::app()->user->id, ':password'=>$pasword_in_db);
					$connection = Yii::app()->db;
					$command = $connection->createCommand($sql_update);
					$command->execute($params);
					$connection->active = false;
					
					Yii::app()->user->setFlash('password', BUtils::T('password_reset_done_msg'));
					$this->refresh();
				}
			} else {
				$model_email->attributes = $_POST['MerchantForm'];
				if ($model_email->validate()) {
					//change email function
					$model_email->new_email = $_POST['MerchantForm']['new_email'];
					//check the new email
					$connection = Yii::app()->db;
					$command = $connection->createCommand('SELECT id FROM tbl_merchant_account WHERE email=:email');
					$row = $command->queryRow(true, array('email' => $model_email->new_email));
					$connection->active = false;
					if (!empty($row)) {
						Yii::app()->user->setFlash('email_failed', BUtils::T('duplicate_email_error_msg', array('{email}'=>$model_email->new_email)));
						$this->refresh();
					} else {
						$sql_update = 'UPDATE tbl_merchant_account SET update_timestamp=NOW(), email=:email WHERE id=:id ';
						$params = array(':id' => Yii::app()->user->id, ':email'=>$model_email->new_email);
						$connection = Yii::app()->db;
						$command = $connection->createCommand($sql_update);
						$command->execute($params);
						$connection->active = false;
						
						Yii::app()->user->setState('email', $model_email->new_email);
						Yii::app()->user->setFlash('email', BUtils::T('email_address_changes_done_msg'));
						$this->refresh();
						
						//Send email change notification to this merchant
					}
				}
			}
		}
		// display the login form
		$this->render('account', array(
			'model_email' => $model_email,
			'model_password' => $model_password,
		));
	}

	public function actionForm()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('profile');
		
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'merchant-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			//save open hours
			if (!empty($_POST['business_hours'])) {
				$sql_hours_delete = 'DELETE FROM tbl_merchant_open_hours WHERE id_merchant=:id_merchant';
				$sql_hours_insert = 'INSERT INTO tbl_merchant_open_hours(id_merchant, week_no, open_hour, close_hour) VALUES (:id_merchant, :week_no, :open_hour, :close_hour)';
				$connection = Yii::app()->db;
				$command = $connection->createCommand($sql_hours_delete);
				$command->execute(array('id_merchant'=>Yii::app()->user->id));
				$command = $connection->createCommand($sql_hours_insert);
				$hittedWeek = array();
				foreach ($_POST['business_hours'] as $v) {
					$aTemp = explode(',', $v);
					if (false === array_search($aTemp[0], $hittedWeek)) {
						$params = array(
							'id_merchant' => Yii::app()->user->id,
							'week_no' => $aTemp[0],
							'open_hour' => $aTemp[1],
							'close_hour' => $aTemp[2],
						);
						$command->execute($params);
						$hittedWeek[] = $aTemp[0];
					}
				}
				$connection->active = false;
			}
			
			$model->attributes = $_POST['MerchantForm'];
			
			//set the address
			if (!empty($_POST['MerchantForm']['address'])) {
				$locArray = explode(',', $_POST['MerchantForm']['address']);
				if (count($locArray) > 0) {
					$model->address = trim($locArray[0]);
				}
			}
			
			//set biz_area string with comma
			if (isset($_POST['MerchantForm']['biz_area'])) {
				$new_biz_area = implode(',', $_POST['MerchantForm']['biz_area']);
				if ($new_biz_area != Yii::app()->user->biz_area) {
					$model->biz_area = $new_biz_area;
					//add new biz area to table tbl_merchant_area_city
					$sql_clear = 'DELETE FROM tbl_merchant_area_city WHERE biz_area=:biz_area AND city_key=:city_key AND country_code=:country_code ';
					$sql_insert = 'INSERT INTO tbl_merchant_area_city (biz_area, city_key, country_code) VALUES (:biz_area, :city_key, :country_code) ';
					$params = array();
					$params[':city_key'] = $model->city;
					$params[':country_code'] = $model->country_code;
					
					$connection = Yii::app()->db;
					foreach ($_POST['MerchantForm']['biz_area'] as $v) {
						$params[':biz_area'] = $v;
						$command = $connection->createCommand($sql_clear);
						$command->execute($params);
						$command = $connection->createCommand($sql_insert);
						$command->execute($params);
					}
					$connection->active = false;
				}
			}
			
			//set unsafe values which are specified by rules method of MerchantForm class
			$model->url_site = $_POST['MerchantForm']['url_site'];
			$model->url_facebook_page = $_POST['MerchantForm']['url_facebook_page'];
			if (!empty($model->address)) {
				$model->latitude = $_POST['MerchantForm']['latitude'];
				$model->longitude = $_POST['MerchantForm']['longitude'];
			}
			$model->currency_code = 'EUR';
			$model->brief = $_POST['MerchantForm']['brief'];
			$model->update_timestamp = new CDbExpression('NOW()');	//update AR
			
			//format phone
			$model->phone = MerchantObject::formatPhoneNumber($model->phone);
			
			// validate user input and redirect to the previous page if valid
			if ($model->save()) {
				//change the category_key of this session
				Yii::app()->user->setState('category_key', $model->category_key);
				Yii::app()->user->setState('name', $model->name);
				Yii::app()->user->setState('address', $model->address);
				Yii::app()->user->setState('biz_area', $model->biz_area);
				Yii::app()->user->setState('postcode', $model->postcode);
				Yii::app()->user->setState('city', $model->city);
				if (!empty($model->latitude)) {
					Yii::app()->user->setState('latitude', $model->latitude);
					Yii::app()->user->setState('longitude', $model->longitude);
				}
				
				$message = '{"success":"'.BUtils::T('profile_save_done_lbl').'"}';
			} else {
				$message = CActiveForm::validate($model);
				
				//trace error
				Yii::log('Merchant '.Yii::app()->user->id.' profile saving is failed! ' . json_encode($model->errors),
					CLogger::LEVEL_ERROR, 'system.web.server');
			}
			
			if (Yii::app()->request->isAjaxRequest) {
				echo $message;
				Yii::app()->end();
			} else {
				Yii::app()->user->setFlash('profile', BUtils::T('profile_save_done_lbl'));
				$this->refresh();
				
				//trace error
				Yii::log('Merchant '.Yii::app()->user->id.' is using the non-ajax submit.',
					CLogger::LEVEL_ERROR, 'system.web.client');
			}
		}
		
		//2. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		
		//3. get merchant's tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
		

		$this->render('form', array(
			'model' => $model,
			'tag' => $tags,
			'aHours' => $hours,
		));
	}
	
	/**
	 * Feature page 
	 */
	public function actionFeature()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('profile');
		
		//2. fetch merchant tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		
		//3. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;

		if (Yii::app()->user->getState('category_key') == 'restaurants') {
			$page = 'feature_restaurants';
		} else $page = 'feature';
		$this->render($page, array(
			'model' => $model,
			'tag' => $tags,
			'aHours' => $hours
		));
	}
	
	/**
	 * Save tags with AJAX.
	 */
	public function actionSaveTags()
	{
		//get post data
		$sql_insert = 'INSERT INTO tbl_merchant_tags(';
		$sql_insert_value = ' VALUES(';
		$params = array();
		foreach ($_POST as $key => $value) {
			if (!empty($value)) {
				if (is_array($value)) {
					$params[$key] = implode(',', $_POST[$key]);
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				} elseif ($key === 'alcohol_license') {
					$params[$key] = $_POST[$key];
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				}
			}
		}
		$sql_insert .= 'id_merchant)';
		$sql_insert_value .= ":id_merchant)";
		$params['id_merchant'] = Yii::app()->user->id;
		
		//print_r(array($sql_insert, $params)); exit;
		
		$sql_delete = 'DELETE FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array('id_merchant'=>Yii::app()->user->id));
		$command = $connection->createCommand($sql_insert . $sql_insert_value);
		$command->execute($params);
		$connection->active = false;
		
		if (Yii::app()->request->isAjaxRequest) {
			echo '{"success":"'.BUtils::T('detail_features_save_done_msg').'"}';
		} else {
			Yii::app()->request->redirect(Yii::app()->createUrl($this->id . '/profile'));
		}
	}
	
	/**
	 * Insert logo picture with AJAX.
	 * 160 x 160 (but keep aspect ratio)
	 */
	public function actionUploadLogo()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
		$sizeLimit = 8 * 1024 * 1024;	// maximum file size in bytes
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'logo_m_' . Yii::app()->user->id, true);
		unset($uploader);
		
		//resize logo picture to 160 x 160 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		$picture->adaptive(160, 160);
		$picture->save($saved_folder . $result['filename']);
		unset($picture);
		
		//delete the original logo picture (not delete, just keep them there)
		
		//insert into menu table
		$sql_menu = 'UPDATE tbl_merchant_account SET url_logo=:url_logo WHERE id=:id';
		$params_menu = array('id'=>Yii::app()->user->id, 'url_logo'=>$url_folder . $result['filename']);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		$connection->active = false;
		$result['url_logo'] = $url_folder . $result['filename'] . '?t=' . time();
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * Insert url_offer_img picture with AJAX.
	 * 96x96 + 640x320
	 */
	public function actionUploadOfferImage()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		$file_postfix = time() . rand(100, 999);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
		$sizeLimit = 8 * 1024 * 1024;	// maximum file size in bytes
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'offer_m_' . $file_postfix, true);
		unset($uploader);
		
		//set thumb
		$thumb = 'thumb_' . $result['filename'];
		
		//resize offer picture to 640 x 360 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		// resize to 640x360: 16:9
		$picture->adaptive(640, 360);
		$picture->save($saved_folder . $result['filename']);
		// resize to 108x108
		$picture->adaptive(192, 108);
		$picture->crop(108, 108);
		$picture->save($saved_folder . $thumb);
		
		unset($picture);
		
		//insert into menu table
		$sql_menu = 'UPDATE tbl_merchant_account SET url_offer_img=:url_offer_img WHERE id=:id';
		$params_menu = array('id'=>Yii::app()->user->id, 'url_offer_img'=>$url_folder . $thumb);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		$connection->active = false;
		$result['url_offer_img'] = BUtils::GetPictureUrl($url_folder . $result['filename']) . '?t=' . time();
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function loadModel($id)
	{
		$model = MerchantForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
}